package app.webchat.payments.agree.wxapi;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import app.webchat.payments.agree.utils.Constants;
import app.webchat.payments.agree.utils.WXPayResultManager;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

	private static final String TAG = "WXPayEntryActivity";
	private IWXAPI api;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);

		api = WXAPIFactory.createWXAPI(this, Constants.WXAPPID);
		api.registerApp(Constants.WXAPPID);
		api.handleIntent(getIntent(), this);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		setIntent(intent);
		api.handleIntent(intent, this);
	}

	@Override
	public void onReq(BaseReq req) {
	}

	@Override
	public void onResp(BaseResp baseResp) {
		Log.w(TAG, "wx result errCode:" + baseResp.errCode
				+ ", errStr " + baseResp.errStr);
		try {
			Intent intent = new Intent();
			intent.setAction(Constants.gamePack+".controlresback");
			Bundle bundle = new Bundle();
			bundle.putString("restype", "wxpay");
			bundle.putString("goodstype", Constants.goodsType);
			bundle.putString("wxerrcode", baseResp.errCode+"");
			bundle.putString("wxerrstr", baseResp.errStr);

			intent.putExtras(bundle);
			startActivity(intent);
		} catch (ActivityNotFoundException e) {
			Log.w(TAG, "回调失败:没找到支付回调Activity");
			e.printStackTrace();
		} catch (Exception e) {
			Log.w(TAG, "异常信息:其他异常");
			e.printStackTrace();
		}

		WXPayResultManager.Instener().notifyWatchers();
	}

	/**
	 * 判断当前微信版本是否支持
	 */
	private  void isSupport(){
		if (api.getWXAppSupportAPI() <  0x21020001) {//wx not support
			Toast.makeText(WXPayEntryActivity.this,"当前微信版本不支持，需要更新", Toast.LENGTH_LONG).show();
		}
	}

}